import { Container, Text, TextStyle, TilingSprite } from 'pixi.js';
import BaseSprite from './BaseSprite.js';
import ResourceManager from '../resource.js';
import AudioManager from '../audio.js';

class ClockSprite extends BaseSprite {
    constructor(app) {
        super(app, 'clock');
        
        this.container = null;
        this.hourText = null;
        this.minuteText = null;
        this.symbolText = null;
        this.clockElapsed = 0;
        this.symbolElapsed = 0;
        this.lastMinute = -1;
        
        this.resources = {
            sand: './sand.png'
        };
    }

    async loadResources() {
        for (const [name, url] of Object.entries(this.resources)) {
            await ResourceManager.load(name, url);
        }
    }

    async init() {
        await this.createClockBackground();
        this.createClockTexts();
    }

    async createClockBackground() {
        const pixel = 18;
        const texture = ResourceManager.get('sand');

        const left = 18 * 5;
        const top = 80;
        const bottom = top + pixel * 10;

        const containerWidth = 640 - 2 * left + 8;
        const tilingSprite = new TilingSprite({
            texture,
            width: containerWidth,
            height: bottom - top
        });
        tilingSprite.x = left - 4;
        tilingSprite.y = top;

        this.addSprite(tilingSprite);

        this.container = new Container();
        this.containerWidth = containerWidth;
        this.containerHeight = bottom - top;
        this.container.x = left;
        this.container.y = top;

        this.addSprite(this.container);
    }

    createClockTexts() {
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();

        const hour = hours < 10 ? '0' + hours : hours;
        const minute = minutes < 10 ? '0' + minutes : minutes;

        // 计算合适的字体大小，让文本填满容器
        const fontSize = this.calculateOptimalFontSize();

        const style = new TextStyle({
            fontFamily: 'MyFont',
            fontSize: fontSize,
            fill: '#ffffff',
            stroke: {
                color: '#000000',
                width: 0
            },
            dropShadow: {
                color: '#000000',
                blur: 0,
                distance: 0
            },
            padding: 0,
            trim: true
        });

        this.hourText = new Text({ text: `${hour}`, style });
        this.minuteText = new Text({ text: `${minute}`, style });
        this.symbolText = new Text({ text: ":", style });

        this.container.addChild(this.hourText);
        this.container.addChild(this.minuteText);
        this.container.addChild(this.symbolText);

        this.lastMinute = minutes;
        
        // 初始布局
        this.layoutClockTexts();
    }

    calculateOptimalFontSize() {
        // 目标文本 "00:00" 作为基准计算
        const testText = "00:00";
        
        // 容器可用宽度和高度（留一些边距）
        const availableWidth = this.containerWidth * 0.9;
        const availableHeight = this.containerHeight * 0.8;
        
        // 从大字体开始测试，逐渐减小直到适合
        for (let fontSize = 120; fontSize >= 20; fontSize -= 5) {
            const testStyle = new TextStyle({
                fontFamily: 'MyFont',
                fontSize: fontSize,
                trim: true
            });
            
            const testTextObj = new Text({ text: testText, style: testStyle });
            
            if (testTextObj.width <= availableWidth && testTextObj.height <= availableHeight) {
                testTextObj.destroy();
                return fontSize;
            }
            
            testTextObj.destroy();
        }
        
        return 20; // 最小字体大小
    }

    layoutClockTexts() {
        // 添加冒号两边的间距
        const spacing = 16; // 冒号两边的间距
        
        // 计算总宽度：小时 + 间距 + 冒号 + 间距 + 分钟
        const totalWidth = this.hourText.width + spacing + this.symbolText.width + spacing + this.minuteText.width;
        const startX = (this.containerWidth - totalWidth) / 2;
        const centerY = (this.containerHeight - this.hourText.height) / 2;

        // 左边：小时
        this.hourText.x = startX;
        this.hourText.y = centerY;

        // 中间：冒号（小时 + 间距）
        this.symbolText.x = startX + this.hourText.width + spacing;
        this.symbolText.y = centerY + 8; // 向下调整6px，让冒号更居中

        // 右边：分钟（小时 + 间距 + 冒号 + 间距）
        this.minuteText.x = startX + this.hourText.width + spacing + this.symbolText.width + spacing;
        this.minuteText.y = centerY;
    }

    update(deltaTime) {
        if (!this.active) return;
        
        this.updateClock(deltaTime);
        this.updateSymbol(deltaTime);
    }

    updateClock(deltaTime) {
        this.clockElapsed += deltaTime / 60;
        if (this.clockElapsed >= 0.5) {
            const now = new Date();
            const hours = now.getHours();
            const minutes = now.getMinutes();

            const hour = hours < 10 ? '0' + hours : hours;
            const minute = minutes < 10 ? '0' + minutes : minutes;

            this.hourText.text = hour;
            
            if (minutes !== this.lastMinute) {
                this.lastMinute = minutes;
                AudioManager.playJumpSound();
            }
            
            this.minuteText.text = minute;
            
            // 文本更新后重新布局
            this.layoutClockTexts();
            
            this.clockElapsed = 0;
        }
    }

    updateSymbol(deltaTime) {
        this.symbolElapsed += deltaTime / 60;
        if (this.symbolElapsed >= 4) {
            this.symbolText.visible = false;
            setTimeout(() => {
                if (this.symbolText) {
                    this.symbolText.visible = true;
                }
            }, 100);
            this.symbolElapsed = 0;
        }
    }

    destroy() {
        this.hourText = null;
        this.minuteText = null;
        this.symbolText = null;
        this.container = null;
        super.destroy();
    }
}

export default ClockSprite;
